package app

import (
	"net/http"
	"team-evaluate/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Ctx *gin.Context
}

type Pager struct {
	Page      int `json:"page"`
	PageSize  int `json:"page_size"`
	TotalRows int `json:"total_rows"`
}

type HttpSuccessResult struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func NewResponse(ctx *gin.Context) *Response {
	return &Response{Ctx: ctx}
}

func (r *Response) ToResponse(data *HttpSuccessResult) {
	if data == nil {
		data = &HttpSuccessResult{
			Code: 200,
			Msg:  "操作成功",
		}
	}
	r.Ctx.JSON(http.StatusOK, data)
}

func (r *Response) ToResponseObj(data interface{}) {
	result := &HttpSuccessResult{
		Code: 200,
		Msg:  "操作成功",
		Data: data,
	}
	r.Ctx.JSON(http.StatusOK, result)
}

func (r *Response) ToResponseList(list interface{}, totalRows int) {
	res := HttpSuccessResult{
		Code: 200,
		Msg:  "操作成功",
		Data: gin.H{
			"list": list,
			"pager": Pager{
				Page:      GetPage(r.Ctx),
				PageSize:  GetPageSize(r.Ctx),
				TotalRows: totalRows,
			},
		},
	}
	r.Ctx.JSON(http.StatusOK, res)
}

func (r *Response) ToErrorResponse(err *errcode.Error) {
	response := gin.H{"code": err.Code(), "msg": err.Msg()}
	details := err.Details()
	if len(details) > 0 {
		response["details"] = details
	}
	r.Ctx.JSON(http.StatusOK, response)
}
